using System;
using System.Collections;
using System.Collections.Generic;
using Cinemachine;
using GardeningSkeleton.Platform;
using GardeningSkeleton.Platform.FXSpace;
using MyFrame.Pool;
using TMPro;
using UnityEngine;
using Plugin.Tool;
using Platform.CharacterData;
using cfg;



public class EntityFX : MonoBehaviour
{
    //通用的特效颜色
    public FXColorDataSO fXColorData;

    [Header("生成技能特效的位置")]
    [HideInInspector] public Transform genSkillParicalPos;

    // 不同角色有不同的特效
    // public FXDataDetail fXData;

    // 临时改变颜色，才调用私有
    private SpriteRenderer sr;
    public Color SrColor
    {
        get { return sr.color; }
        set
        {
            sr.color = value;
            currentColor = value;
        }
    }
    private Color originColor;
    private Color currentColor = Color.white;

    [Header("Flash FX")]
    [SerializeField] private Material hitMat;
    private Material originMat;

    public GameObject afterImagePrefab;

    #region 生命周期
    void Awake()
    {
        sr = GetComponentInChildren<SpriteRenderer>();
        originColor = sr.color;
        originMat = sr.material;
        
        fXColorData = AAMgr.LoadAsset<FXColorDataSO>("FXColorData");
        hitMat = AAMgr.LoadAsset<Material>("FlashFXMaterial");

        genSkillParicalPos = transform.Find("GenSkillParicalPos");
    }
    #endregion

    /// <summary>
    /// 闪白
    /// </summary>
    public void FlashFX()
    {
        sr.material = hitMat;

        sr.color = Color.white;
        ZTimer.SetTimeout(0.1f, () =>
        {
            sr.material = originMat;
            sr.color = currentColor;
        });
    }

    // 闪红
    public void RedColorBlink()
    {
        ZTimer.SetInterval(0.1f, RedColorBlinkAsync);
    }
    private void RedColorBlinkAsync()
    {
        if (sr.color != Color.white)
            sr.color = Color.white;
        else
            sr.color = Color.red;
    }

    #region  打击特效
    /// <summary>
    ///  生成位置是  敌人碰撞盒  距离  武器碰撞端点  最近的点
    ///  分三步  打击特效   血液粒子效果+受击特效
    /// </summary>
    /// <param name="other"></param>
    /// <param name="target"></param>
    /// <param name="isCrit"></param>
    /// <param name="isHeavy"> 是否重攻击</param>
    public void CreateHit(Collider2D other, CharacterStats target, bool isCrit = false)
    {
        if (Stats.currentHitEffect == HitEffect.None) return;
        Vector3 edgePoint = Tool.GetCollider2DEdgePoint(transform.GetChild(0).GetComponentInChildren<CapsuleCollider2D>(), Entity.facingRight);
        var hitPosition = other.ClosestPoint(edgePoint);

        Tool.GetEffectRandomPosAndRotation(Entity, hitPosition, out Vector3 randomPosition, out Quaternion effectRotation);

        if (isCrit) EffectMgr.Instance.AddWorldEffect(Stats.currentHitEffect, randomPosition, effectRotation, scale: 1.5f);
        else EffectMgr.Instance.AddWorldEffect(Stats.currentHitEffect, randomPosition, effectRotation);

        //根据种族创建受击特效  --使用约定好的命名格式
        string onHitType = target.race.ToString() + "OnHitEffect";
        // 活体种类，流血
        if (target.IsLivingBody)
        {
            //钝击不流血
            if (Stats.currentAttackDamageType == AttackDamageType.Blunt)
            {
                onHitType = null;
            }
            else
            {
                //根据攻击类型生成不同的出血效果
                onHitType = "Blood" + Stats.currentAttackDamageType.ToString() + "OnHitEffect";
                //生成血液粒子特效  同样根据攻击类型
                var bloodParitcleType = BloodParticleType.Normal;
                switch (Stats.currentAttackDamageType)
                {
                    case AttackDamageType.Cut:
                        bloodParitcleType = BloodParticleType.Normal;
                        break;
                    case AttackDamageType.Pierece:
                        bloodParitcleType = BloodParticleType.Line;
                        break;
                    case AttackDamageType.Stab:
                        bloodParitcleType = BloodParticleType.Point;
                        break;
                }
                EffectMgr.Instance.AddWorldEffect(bloodParitcleType, randomPosition, effectRotation);

                //todo 判断当前环境，如果是室内，就在背景涂抹一层血迹 没有合适的图片

            }
        }

        if (onHitType.NotNullOrEmpty())
            EffectMgr.Instance.AddWorldEffect(onHitType, randomPosition, effectRotation);

    }

    #endregion

    #region  技能特效
    GameObject currentSkillParticle;
    public void CancelColorChange()
    {
        ZTimer.ClearTimer(RedColorBlinkAsync);
        SrColor = Color.white;

        if (currentSkillParticle != null)
        {
            EffectMgr.Instance.Release(currentSkillParticle);
            currentSkillParticle = null;
        }
    }
    public void IceColorFx()
    {
        SrColor = IceColor;

        // 确保特效唯一性  
        if (currentSkillParticle == null)
            currentSkillParticle = EffectMgr.Instance.AddEffect(ParticleFXType.Fronze, transform,
            genSkillParicalPos.localPosition, Quaternion.identity);
    }
    public void FireColorFx()
    {
        SrColor = SrColor == FireColor[0] ? FireColor[1] : FireColor[0];
    }

    public void ElectricColorFx()
    {
        SrColor = SrColor == ElectricColor[0] ? ElectricColor[1] : ElectricColor[0];
    }

    #endregion

    #region  冲刺残影
    // todo 改成全代码
    public void CreateAfterImageStart()
    {
        ZTimer.SetInterval(0.05f, CreateAfterImage);
    }

    public void CreateAfterImageStop()
    {
        ZTimer.ClearTimer(CreateAfterImage);
    }
    private void CreateAfterImage()
    {
        GameObject newAfterImage = Instantiate(afterImagePrefab, transform.position, transform.rotation);
        newAfterImage.GetComponent<AfterImageFx>()
        .Setup(GetComponentInChildren<SpriteRenderer>(), 1f);
    }
    #endregion

    #region 伤害数字
    public void CreatePop(string text)
    {
        float randomX = UnityEngine.Random.Range(-0.3f, 0.3f);
        float randomY = UnityEngine.Random.Range(1f, 2f);

        var realPos = Entity.GetRealPos() + new Vector3(randomX, randomY, 0);
        // realPos = Camera.main.WorldToScreenPoint(realPos);
        if(realPos == Vector3.zero) 
        {
            Debug.Log("realPos == 0");
        }
        var pop = PoolMgr.Instance.GetObj("PopText", realPos, Quaternion.identity);
        pop.GetComponent<TextMeshPro>().text = text;
    }
    #endregion

    #region  简写
    public Color IceColor => fXColorData.iceColor;
    public Color[] ElectricColor => fXColorData.electricColor;
    public Color[] FireColor => fXColorData.fireColor;

    private Entity Entity => GetComponent<Entity>();
    private CharacterStats Stats => GetComponent<CharacterStats>();
    #endregion
}
